package com.tt.fashionWebSite.util;

import org.apache.log4j.Logger;
import org.ini4j.Wini;
import org.ini4j.Profile;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Properties;

/**
 * Created by isoft-work 5 on 12/5/2014.
 */
public class AutoMailTask {
   private final static Logger logger = Logger.getLogger(AutoMailTask.class);
   private String fromEmail;
   private String passWord;
   private String smtpHost;
   private String smtpPort;
   private String protocol ;
   private Session session = null;

   public AutoMailTask () {
      getEmailConfig();

//      Email Start
      Properties props = new Properties();
      if ("tls".equalsIgnoreCase(protocol)) {
         props.put("mail.smtp.starttls.enable", "true");
      } else if ("ssl".equalsIgnoreCase(protocol)) {
         props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
         props.put("mail.smtp.socketFactory.port", smtpPort);
      }
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.host", smtpHost);
      props.put("mail.smtp.port", smtpPort);

      Authenticator auth = new Authenticator() {
         //override the getPasswordAuthentication method
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromEmail, passWord);
         }
      };

      session = Session.getDefaultInstance(props, auth);
   }

   private void getEmailConfig() {
      try {
         String pathSettingFile = ISSConstants.webappDir.getCanonicalPath() + "/setting.ini";
         File settingFile = new File(pathSettingFile);
         Wini ini = new Wini(settingFile);

         Profile.Section sec = ini.get("Email");

         if (sec != null && sec.containsKey("Username")) {
            this.fromEmail = sec.get("Username");
         }

         if (sec != null && sec.containsKey("Password")) {
            this.passWord = CryptographyDataUtils.decryptWithAES(sec.get("Password"));
         }

         if (sec != null && sec.containsKey("Smtp_Host")) {
            this.smtpHost = sec.get("Smtp_Host");
         }

         if (sec != null && sec.containsKey("Smtp_Port")) {
            this.smtpPort = sec.get("Smtp_Port");
         }

         if (sec != null && sec.containsKey("Protocol")) {
            this.protocol = sec.get("Protocol");
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public void sendMail(String nameSend,String toEmail, String subject, String body) {
      try{
         MimeMessage msg = new MimeMessage(session);
         msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
         msg.addHeader("format", "flowed");
         msg.addHeader("Content-Transfer-Encoding", "8bit");

         msg.setFrom(new InternetAddress(fromEmail, nameSend));

//         msg.setReplyTo(InternetAddress.parse(toEmail, false));

         msg.setSubject(subject, "UTF-8");

         msg.setSentDate(new Date());

         msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

         msg.setContent(body, "text/html; charset=utf-8");

         // Send message
         Transport.send(msg);
         logger.info("EMail Sent Successfully !");
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }

   public void sendAttachmentEmail(String nameSend,String toEmail, String subject, String body, String pathFile) {
      try{
         MimeMessage msg = new MimeMessage(session);
         msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
         msg.addHeader("format", "flowed");
         msg.addHeader("Content-Transfer-Encoding", "8bit");

         msg.setFrom(new InternetAddress(fromEmail, nameSend));

//         msg.setReplyTo(InternetAddress.parse(toEmail, false));

         msg.setSubject(subject, "UTF-8");

         msg.setSentDate(new Date());

         msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

         // Create the message body part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText(body);

         // Create a multipart message for attachment
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Second part is attachment
         messageBodyPart = new MimeBodyPart();
         DataSource source = new FileDataSource(pathFile);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(pathFile);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         msg.setContent(multipart);

         // Send message
         Transport.send(msg);
         logger.info("EMail Sent Successfully !");
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }
}
